package org.example.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.models.LoginUser;
import org.example.models.R;
import org.example.utils.JwtUtils;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SecurityAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    ObjectMapper objectMapper= new ObjectMapper();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
//        response.getWriter().print("登录成功");
        LoginUser principal =(LoginUser) authentication.getPrincipal();
        String token=JwtUtils.generateToken(principal.getUser().getId(), principal.getUsername());
        R<Object> success = R.success(200, "登录成功",token);
        String json = objectMapper.writeValueAsString(success);
        response.getWriter().print(json);
    }
}
